import JSEncrypt from 'jsencrypt'
import { savePublicKey, readPublicKey } from '@/utils/auth'
import { getPublicKey as getUserPublicKey } from '@/api/user'

export async function encrypt(value) {
  let key = readPublicKey()
  console.log(key)
  try {
    // 如果没有公钥，则请求获取公钥
    if (!key || key === 'undefined') {
      const result = await getUserPublicKey()
      console.log('公钥获取结果：', result)
      key = result.data.publicKey
      // 去除公钥中的空格和换行符
      key = key.replace(/\. +/g, '')
      key = key.replace(/[\r\n]/g, '')
      console.log('公钥获取成功：', key)
      savePublicKey(key)
    }
    // 加密
    console.log(1)
    const encrypt = new JSEncrypt()
    encrypt.setPublicKey(key)
    return encrypt.encrypt(value)
  } catch (err) {
    console.log(err)
  }
}
